package redis

import (
	"gin-web/app/core/config"
	"github.com/go-redis/redis"
	"sync"
	"time"
)

var (
	lock     sync.RWMutex
	instance = make(map[string]*redis.Client)
)

// Load 连接redis
func Load(cfg config.RedisItem, key string) *redis.Client {
	//加锁
	lock.RLock()
	if _, ok := instance[key]; ok {
		defer lock.RUnlock()
		return instance[key]
	}
	lock.RUnlock()

	//加锁，连接数据库
	lock.Lock()
	defer lock.Unlock()
	//double check
	if _, ok := instance[key]; ok {
		return instance[key]
	}

	//连接服务
	instance[key] = conn(cfg)
	return instance[key]
}

func conn(cfg config.RedisItem) *redis.Client {
	if cfg.Addr == "" {
		panic("redis地址不能为空")
	}

	client := redis.NewClient(&redis.Options{
		Addr:         cfg.Addr,
		PoolSize:     cfg.PoolSize,
		Password:     cfg.Password,
		IdleTimeout:  time.Duration(cfg.IdleTimeout) * time.Millisecond,
		ReadTimeout:  time.Duration(cfg.ReadTimeout) * time.Millisecond,
		WriteTimeout: time.Duration(cfg.WriteTimeout) * time.Millisecond,
		MaxRetries:   cfg.Retries,
		MinIdleConns: cfg.MinIdleConns,
		DB:           cfg.Db,
	})

	_, err := client.Ping().Result()
	if err != nil {
		panic("redis连接失败：" + err.Error())
	}

	return client
}
